<?php
/**
* @package SefTranslate
* Date: 2011/04/01
* Development Aleksey Pakholkov, Andrey Kvasnevskiy - OrdaSoft(http://ordasoft.com)
* @copyright 2011 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru);
* Homepage: http://www.ordasoft.com
* @version: 2.0.0 Pro
*/

if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
require_once(JPATH_SITE.'/components/com_seftranslate/GTranslate.php');
require_once(JPATH_SITE.'/components/com_seftranslate/sefurl.class.php');  
require_once(JPATH_SITE.'/components/com_seftranslate/sefentity.class.php' );
require_once(JPATH_SITE.'/components/com_seftranslate/languages.conf.php');
$GLOBALS['all_elements'] = $all_elements = array ();
$GLOBALS['glob_gt_id'] = 0;

function array_text_translate($arr_text,$lang_from='en',$lang_to='ru')
{

  global  $settings;

  $translator = $settings['translator'] ;
  $ret_value = array();
  for($kk=0; $kk < count($arr_text); $kk++ ){
    
    mb_detect_order("UTF-16, UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
    $ret_value[] = mb_convert_encoding($arr_text[$kk], 'HTML-ENTITIES', mb_detect_encoding($arr_text[$kk]));
  }  

  switch($translator){
    case 'bing' : 
      $ret_value = bing_array_text_translate($ret_value,$lang_from,$lang_to);
      break;
    case 'gtranslate' : 
      $ret_value = gtranslate_array_text_translate($ret_value,$lang_from,$lang_to);
   
      break;
    default : 
      echo "some error in translator choose, please connect to developers";
      break;
  }
  return $ret_value;
}

function bing_array_text_translate($arr_text,$lang_from='en',$lang_to='ru'){
  global  $settings,$seftranslate_error;
  
  //DBQuery
  $database =& JFactory::getDBO();
  
  $ret_value = $arr_text;
  $lang_from2 = $lang_from;
  $lang_to2 = $lang_to;
  if( $lang_from == 'pt-PT' )  $lang_from2 = 'pt';
  if( $lang_to == 'pt-PT' )  $lang_to2 = 'pt';
  if( $lang_from == 'zh-CN' )  $lang_from2 = 'zh-CHS';
  if( $lang_to == 'zh-CN' )  $lang_to2 = 'zh-CHS';
  if( $lang_from == 'zh-TW' )  $lang_from2 = 'zh-CHT';
  if( $lang_to == 'zh-TW' )  $lang_to2 = 'zh-CHT';
  
  $params = array();
  $params['texts'] = $arr_text;
  $params['from'] = $lang_from2;
  $params['to'] = $lang_to2;
  $params['contentType'] = "text/html";
  $params['appId']=$settings['appId'];
  
  try
  {
    $bing_client = new SoapClient("http://api.microsofttranslator.com/V2/SOAP.svc");
    $result = $bing_client->TranslateArray($params);
    //$ret_value = $result->TranslateArrayResult->TranslateArrayResponse;
    
  }
  catch(Exception $e)
  {
    if($settings['debug'] ) { throw $e; exit;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
  }
  
  $ret_value = array();
  for($kk=0; $kk < count($arr_text); $kk++ ){
    
    $TranslatedText = "";
    if(is_array($result->TranslateArrayResult->TranslateArrayResponse )  )
      $TranslatedText = $result->TranslateArrayResult->TranslateArrayResponse[$kk]->TranslatedText ;
    else   $TranslatedText = $result->TranslateArrayResult->TranslateArrayResponse->TranslatedText ;
    $ret_value[] = $TranslatedText ;
    
    $is_translated_before = get_text_translated($arr_text[$kk],$lang_from,$lang_to);
    if($is_translated_before !== false || trim($TranslatedText) == "" ) continue;
    
    //save to database
    $efentity = new mosSefentity($database);
    $efentity->hash = md5( $arr_text[$kk] );
    $efentity->entity_text = $TranslatedText ;
    $efentity->lang_from = $lang_from ;
    $efentity->lang_to = $lang_to ;
    $efentity->hits = 1 ;
    $efentity->date = date("Y-m-d H:i:s");
    $efentity->checkin();
    $efentity->store();
  }
  return $ret_value;
}


function gtranslate_array_text_translate($arr_text,$lang_from='en',$lang_to='ru'){
  global  $gt, $l_func,$settings,$seftranslate_error;
  $database =& JFactory::getDBO();
  $ret_array = array();
  $ret_value = $arr_text;
  if(isset($GLOBALS['gt']) ){
    try
    {

      $ret_value = $gt->$l_func($arr_text);
   
    }
    catch(Exception $e)
    {
      if($settings['debug'] ) { throw $e;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
    }
  
  } else {
    $gt = new Gtranslate;

    if (!empty($settings['api_translate'])) {


//      $gt->setApiKey('ABQIAAAARBki4JWk0Cwz-v6GlQ90wBRTxlZd-7gfuqQumodWhI9M82S_fRQ5OJFZp4v4oNXri4eZjoah2n4--w');
      $gt->setApiKey($settings['api_translate']);
    }
    if($settings['userip']) $gt->setUserIp( $_SERVER['REMOTE_ADDR'] );
    $gt->setRequestType('curl');
    $gt->setApiVersion(2);
    $gt->setUrl('https://www.googleapis.com/language/translate/v2');

    $lang_list=parse_ini_file(JPATH_SITE.'/components/com_seftranslate/languages.ini');
    $lang_from2 = array_search($lang_from,$lang_list);
    $lang_to2 = array_search($lang_to,$lang_list);  
  
    $l_func=$lang_from2."_to_".$lang_to2;
    
    $GLOBALS['gt'] = $gt ;
    $GLOBALS['l_func'] = $l_func ;

    try
    {
              
      $ret_array = $gt->$l_func($arr_text);
    }
    catch(Exception $e)
    { 
      if($settings['debug'] ) { throw $e;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
    }
  }
  
  $ret_value = array();
  for($kk=0; $kk < count($arr_text); $kk++ ){
    
    $ret_value[] = $ret_array[$kk]->translatedText ;

    $is_translated_before = get_text_translated($arr_text[$kk],$lang_from,$lang_to);
    if($is_translated_before !== false || trim($ret_array[$kk]->translatedText) == "" ) continue;
    
    //save to database
    $efentity = new mosSefentity($database);
    $efentity->hash = md5( $arr_text[$kk] );
    $efentity->entity_text = $ret_array[$kk]->translatedText ;
    $efentity->lang_from = $lang_from ;
    $efentity->lang_to = $lang_to ;
    $efentity->hits = 1 ;
    $efentity->date = date("Y-m-d H:i:s");
    $efentity->checkin();
    $efentity->store();
  }
  return $ret_value;

}



function text_translate($text,$lang_from='en',$lang_to='ru')
{
  global  $settings;
  
  if(trim($text) == "" ) return $text;
  if( is_special($text) ) return $text;
  mb_detect_order("UTF-16, UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
  $text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));

  //check translated text in database
  $ret_value = get_text_translated($text,$lang_from,$lang_to);
  if($ret_value !== false ) return $ret_value;
  
  
  $translator = $settings['translator'] ;
  $ret_value = $text;
  switch($translator){
    case 'bing' : 
      $ret_value = bing_text_translate($text,$lang_from,$lang_to);
      break;
    case 'gtranslate' : 
      $ret_value = gtranslate_text_translate($text,$lang_from,$lang_to);
      break;
    default : 
      echo "some error in translator choose, please connect to developers";
      break;
  }
  return $ret_value;
}

function bing_text_translate($text,$lang_from='en',$lang_to='ru'){
  global  $settings,$seftranslate_error;
  
  //DBQuery
  $database =& JFactory::getDBO();
  
  $ret_value = $text;
  $lang_from2 = $lang_from;
  $lang_to2 = $lang_to;
  if( $lang_from == 'pt-PT' )  $lang_from2 = 'pt';
  if( $lang_to == 'pt-PT' )  $lang_to2 = 'pt';
  if( $lang_from == 'zh-CN' )  $lang_from2 = 'zh-CHS';
  if( $lang_to == 'zh-CN' )  $lang_to2 = 'zh-CHS';
  if( $lang_from == 'zh-TW' )  $lang_from2 = 'zh-CHT';
  if( $lang_to == 'zh-TW' )  $lang_to2 = 'zh-CHT';
  
  $params = array();
  $params = array();
  $params['text'] = $text;
  $params['from'] = $lang_from2;
  $params['to'] = $lang_to2;
  $params['contentType'] = "text/html";
  $params['appId']=$settings['appId'];  
 
  
  try
  {
    $bing_client = new SoapClient("http://api.microsofttranslator.com/V2/SOAP.svc");
    $result = $bing_client->Translate($params);
    $ret_value = $result->TranslateResult;
  }
  catch(Exception $e)
  {
    if($settings['debug'] ) { throw $e; exit;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
  }
  if(trim($ret_value) == "" ) return $ret_value;;
  
  //save to database
  $efentity = new mosSefentity($database);
  $efentity->hash = md5($text);
  $efentity->entity_text = $ret_value;
  $efentity->lang_from = $lang_from ;
  $efentity->lang_to = $lang_to ;
  $efentity->hits = 1 ;
  $efentity->date = date("Y-m-d H:i:s");
  $efentity->checkin();
  $efentity->store();
  
  return $ret_value;
}

function gtranslate_text_translate($text,$lang_from='en',$lang_to='ru'){
  global  $gt, $l_func,$settings,$seftranslate_error;
  //DBQuery
  $database =& JFactory::getDBO();
  
  $ret_value = $text;
  if(isset($GLOBALS['gt']) ){


    try
    {
      $ret_value = $gt->$l_func($text);
      $ret_value = $ret_value[0]->translatedText;
    }
    catch(Exception $e)
    {
      if($settings['debug'] ) { throw $e; exit;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
    }
  
  } else {
    $gt = new Gtranslate;
    if (!empty($settings['api_translate'])) {
      //$gt->setApiKey('ABQIAAAARBki4JWk0Cwz-v6GlQ90wBRTxlZd-7gfuqQumodWhI9M82S_fRQ5OJFZp4v4oNXri4eZjoah2n4--w');
      $gt->setApiKey($settings['api_translate']);
    }
    if($settings['userip']) $gt->setUserIp( $_SERVER['REMOTE_ADDR'] );
    $gt->setRequestType('curl');
    $gt->setApiVersion(2);
    $gt->setUrl('https://www.googleapis.com/language/translate/v2');
    
    $lang_list=parse_ini_file(JPATH_SITE.'/components/com_seftranslate/languages.ini');
    $lang_from2 = array_search($lang_from,$lang_list);
    $lang_to2 = array_search($lang_to,$lang_list);  
  
    $l_func=$lang_from2."_to_".$lang_to2;
    
    $GLOBALS['gt'] = $gt ;
    $GLOBALS['l_func'] = $l_func ;

    try
    {
      $ret_value = $gt->$l_func($text);
      $ret_value = $ret_value[0]->translatedText;
    }
    catch(Exception $e)
    { 
      if($settings['debug'] ) { throw $e; exit;}
      else {
        $seftranslate_error = true;
        return $ret_value;
      }
    }
  }
  if(trim($ret_value) == "" ) return $ret_value;;
  
  //save to database
  $efentity = new mosSefentity($database);
  $efentity->hash = md5($text);
  $efentity->entity_text = $ret_value;
  $efentity->lang_from = $lang_from ;
  $efentity->lang_to = $lang_to ;
  $efentity->hits = 1 ;
  $efentity->date = date("Y-m-d H:i:s");
  $efentity->checkin();
  $efentity->store();
  
  return $ret_value;
}

function get_text_translated($text,$lang_from='en',$lang_to='ru'){
  
  //DBQuery
  $database =& JFactory::getDBO();
  if(trim($text) == "" ) return $text;
  if( is_special($text) ) return $text;
  mb_detect_order("UTF-16, UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
  $text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));


  //check translated text in database
  $hash = md5($text);
  $efentity = new mosSefentity($database);
  $efentity = $efentity->loadForHash($hash,$lang_from,$lang_to);
  if( $efentity != null ) {
    $ret_value = $efentity->entity_text;
    $efentity->hits = $efentity->hits + 1 ;
    $efentity->date = date("Y-m-d H:i:s");
    $efentity->store();
    return $ret_value;
  }
  
  return false;
}

function is_special($text){

$HTML_ENTS=array("&quot;", "&amp;", "&apos;", "&lt;", "&gt;", "&nbsp;", "&iexcl;", "&cent;",
"&pound;","curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;",
"&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;",
"&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;",
"&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;",
"&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;",
"&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;",
"&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;",
"&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;",
"&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;",
"&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;",
"&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;",
"&yacute;", "&thorn;", "&yuml;", "&OElig;", "&oelig;", "&Scaron;", "&scaron;", "&Yuml;",
"&fnof;", "&circ;", "&tilde;", "&Alpha;", "&Beta;", "&Gamma;", "&Delta;", "&Epsilon;",
"&Zeta;", "&Eta;", "&Theta;", "&Iota;", "&Kappa;", "&Lambda;", "&Mu;", "&Nu;", "&Xi;",
"&Omicron;", "&Pi;", "&Rho;", "&Sigma;", "&Tau;", "&Upsilon;", "&Phi;", "&Chi;", "&Psi;",
"&Omega;", "&alpha;", "&beta;", "&gamma;", "&delta;", "&epsilon;", "&zeta;", "&eta;",
"&theta;", "&iota;", "&kappa;", "&lambda;", "&mu;", "&nu;", "&xi;", "&omicron;", "&pi;",
"&rho;", "&sigmaf;", "&sigma;", "&tau;", "&upsilon;", "&phi;", "&chi;", "&psi;", "&omega;",
"&thetasym;", "&upsih;", "&piv;", "&ensp;", "&emsp;", "&thinsp;", "&zwnj;", "&zwj;", "&lrm;",
"&rlm;", "&ndash;", "&mdash;", "&lsquo;", "&rsquo;", "&sbquo;", "&ldquo;", "&rdquo;",
"&bdquo;", "&dagger;", "&Dagger;", "&bull;", "&hellip;", "&permil;", "&prime;", "&Prime;",
"&lsaquo;", "&rsaquo;", "&oline;", "&frasl;", "&euro;", "&image;", "&weierp;", "&real;",
"&trade;", "&alefsym;", "&larr;", "&uarr;", "&rarr;", "&darr;", "&harr;", "&crarr;", "&lArr;",
"&uArr;", "&rArr;", "&dArr;", "&hArr;", "&forall;", "&part;", "&exist;", "&empty;", "&nabla;",
"&isin;", "&notin;", "&ni;", "&prod;", "&sum;", "&minus;", "&lowast;", "&radic;", "&prop;",
"&infin;", "&ang;", "&and;", "&or;", "&cap;", "&cup;", "&int;", "&there4;", "&sim;", "&cong;",
"&asymp;", "&ne;", "&equiv;", "&le;", "&ge;", "&sub;", "&sup;", "&nsub;", "&sube;", "&supe;",
"&oplus;", "&otimes;", "&perp;", "&sdot;", "&lceil;", "&rceil;", "&lfloor;",
"&rfloor;", "&lang;", "&rang;", "&loz;", "&spades;", "&clubs;", "&hearts;", "&diams;");

  $text = trim($text);
  if( in_array(trim($text),$HTML_ENTS ) ) return true;

  $HTML_ENTS2 = array();
  foreach($HTML_ENTS as $ent){
    $HTML_ENTS2[] = html_entity_decode($ent); 
  }

  $text = html_entity_decode($text);
  
  for($kk = 0; $kk < strlen($text); $kk++ )
    if( !in_array($text[$kk],$HTML_ENTS2 ) ) return false;
  
  return true;
}
